const express = require('express')
const router = express.Router();
const mySql = require('../../config/db')
// 处理时间搓的
// const moment = require('./node_modules/moment')
// 创建配置信息
router.post('/', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const { type, label, name } = req.body;
  const uId = req.headers.authorization.replace(/[^0-9]/ig, "")
  let time = Math.round((new Date().getTime()) / 1000);
  const sqlInsert = 'insert into options(u_id,type,label,value,time) values(?,?,?,?,?)';
  mySql.query(sqlInsert, [uId, type, label, name, time], (err, data) => {
    if (err) {
      reRes.message = '新增失败';
      reRes.data = null;
      res.json(reRes)
    } else {
      // 判断是否执行成功
      if (data.affectedRows === 1) {
        reRes.message = '新增成功';
        reRes.data = data;
        res.json(reRes)
      } else {
        reRes.message = '新增失败';
        reRes.data = null;
        res.json(reRes)
      }
    }
  })

})
// })
// 获取配置信息列表
router.get('/', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  let sqlList = '';
  if (req.query.data) {
    const types = req.query.data.join(',');
    sqlList = `select * from options where type in (${types}) order by id desc`;
  } else {
    sqlList = 'select * from options order by id desc';

  }
  mySql.query(sqlList, (err, data) => {
    if (err) {
      reRes = {
        status: 200,
        message: "获取失败",
        data: null
      }
      res.json(reRes)
    } else {
      if (data.length > 0) {
        reRes.message = '获取成功';
        reRes.data = data;
        res.json(reRes);
      } else {
        reRes.message = '获取成功';
        reRes.data = [];
        res.json(reRes);
      }
    }
  })



})
// 删除配置信息
router.delete('/', (req, res) => {
  const reRes = {
    status: 200,
    message: "",
    data: null
  }
  const id = req.query.id;
  const uId = req.headers.authorization.replace(/[^0-9]/ig, "")
  const sqlSelect = "select * from options where id = ?";
  mySql.query(sqlSelect, [id], (err, data) => {
    if (err) {
      reRes.message = "删除失败"
      reRes.data = null;
      res.json(reRes);
    } else {
      if (data.length === 0) {
        reRes.message = "文件不存在"
        reRes.data = null;
        res.json(reRes);
      } else {
        const sqlDelete = `delete from options where id = ${id}`;
        mySql.query(sqlDelete, (err, data) => {
          if (err) {
            reRes.message = "删除失败"
            res.json(reRes);
          } else {
            // 判断是否执行成功 
            if (data.affectedRows == 1) {
              reRes.message = "删除成功"
              reRes.data = data;
              res.json(reRes);
            } else {
              reRes.message = "删除失败"
              res.json(reRes);
            }
          }
        })
      }
    }
  })
})

module.exports = router;